package com.xiehua.task.job;

import akka.actor.ActorRef;
import com.xiehua.task.actor.cmd.Cmd;
import com.xiehua.task.job.bucket.DelayBucket;
import com.xiehua.task.job.bucket.FixedBucket;
import com.xiehua.task.job.pool.DelayJob;
import com.xiehua.task.job.pool.FixedJob;
import com.xiehua.task.job.pool.Job;
import com.xiehua.task.redis.RedisTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.util.List;

import static com.xiehua.task.actor.cmd.Cmd.CMD_TASK_READY;


/**
 * 轮询器
 * **/
public class Timer  extends Thread{

    private static final Logger logger = LoggerFactory.getLogger(Timer.class);

    private ActorRef taskReadyActor;

    public Timer(ActorRef taskReadyActor){
        this.taskReadyActor = taskReadyActor;
    }

    @Override
    public void run() {
        while(true){
            Jedis jedis= RedisTemplate.getJedis();
            try {
                DelayBucket delayBucket = new DelayBucket(jedis);
                //延迟任务
                List<DelayJob> delayJobs = delayBucket.queryCurrentJob();
                if(delayJobs != null && delayJobs.size() > 0){
                    Cmd<List<DelayJob>> cmd = new Cmd<>(CMD_TASK_READY,delayJobs);
                    taskReadyActor.tell(cmd,ActorRef.noSender());
                }
                //定时任务
                FixedBucket fixedBucket = new FixedBucket(jedis);
                List<FixedJob> fixedJobs = fixedBucket.queryCurrentJob();
                if(fixedJobs != null && fixedJobs.size() > 0){
                    Cmd<List<FixedJob>> cmd = new Cmd<>(CMD_TASK_READY,fixedJobs);
                    taskReadyActor.tell(cmd,ActorRef.noSender());
                }
                //移除不可用主机

                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                RedisTemplate.closeRedis(jedis);
            }
        }
    }




}
